import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';

/// 🖼️ 统一的缓存图片组件
/// 
/// 封装 CachedNetworkImage，提供一致的图片加载体验
/// - ✅ 自动缓存到本地
/// - ✅ 支持占位符
/// - ✅ 支持错误处理
/// - ✅ 无渐变效果（即时显示）
/// - ✅ 性能优化
class CachedImage extends StatelessWidget {
  /// 图片URL
  final String imageUrl;
  
  /// 宽度
  final double? width;
  
  /// 高度
  final double? height;
  
  /// 适配方式
  final BoxFit fit;
  
  /// 是否显示占位符
  final bool showPlaceholder;
  
  /// 占位符背景色
  final Color? placeholderColor;
  
  /// 占位符图标
  final IconData? placeholderIcon;
  
  /// 占位符图标大小
  final double placeholderIconSize;
  
  /// 错误图标
  final IconData errorIcon;
  
  /// 错误图标大小
  final double errorIconSize;
  
  /// 圆角半径
  final double? borderRadius;
  
  /// 是否显示圆形（头像模式）
  final bool isCircle;
  
  /// 内存缓存宽度（用于优化性能）
  final int? memCacheWidth;
  
  /// 内存缓存高度（用于优化性能）
  final int? memCacheHeight;

  const CachedImage({
    super.key,
    required this.imageUrl,
    this.width,
    this.height,
    this.fit = BoxFit.cover,
    this.showPlaceholder = true,
    this.placeholderColor,
    this.placeholderIcon,
    this.placeholderIconSize = 40,
    this.errorIcon = Icons.error_outline,
    this.errorIconSize = 40,
    this.borderRadius,
    this.isCircle = false,
    this.memCacheWidth,
    this.memCacheHeight,
  });

  @override
  Widget build(BuildContext context) {
    // 如果URL为空，直接显示占位符
    if (imageUrl.isEmpty) {
      return _buildPlaceholder();
    }

    Widget imageWidget = CachedNetworkImage(
      imageUrl: imageUrl,
      width: width,
      height: height,
      fit: fit,
      memCacheWidth: memCacheWidth,
      memCacheHeight: memCacheHeight,
      // 🔥 关键：禁用淡入动画，立即显示图片
      fadeInDuration: Duration.zero,
      fadeOutDuration: Duration.zero,
      // 🔥 占位符：不显示加载动画，只显示纯色背景
      placeholder: showPlaceholder
          ? (context, url) => _buildPlaceholder()
          : null,
      // 🔥 错误处理：显示错误图标
      errorWidget: (context, url, error) => _buildErrorWidget(),
    );

    // 应用圆角或圆形效果
    if (isCircle) {
      return ClipOval(child: imageWidget);
    } else if (borderRadius != null && borderRadius! > 0) {
      return ClipRRect(
        borderRadius: BorderRadius.circular(borderRadius!),
        child: imageWidget,
      );
    }

    return imageWidget;
  }

  /// 构建占位符
  Widget _buildPlaceholder() {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        color: placeholderColor ?? Colors.grey[300],
        shape: isCircle ? BoxShape.circle : BoxShape.rectangle,
        borderRadius: isCircle
            ? null
            : (borderRadius != null ? BorderRadius.circular(borderRadius!) : null),
      ),
      child: Center(
        child: Icon(
          placeholderIcon ?? Icons.image_outlined,
          size: placeholderIconSize,
          color: Colors.grey[600],
        ),
      ),
    );
  }

  /// 构建错误组件
  Widget _buildErrorWidget() {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        color: Colors.grey[200],
        shape: isCircle ? BoxShape.circle : BoxShape.rectangle,
        borderRadius: isCircle
            ? null
            : (borderRadius != null ? BorderRadius.circular(borderRadius!) : null),
      ),
      child: Center(
        child: Icon(
          errorIcon,
          size: errorIconSize,
          color: Colors.grey[400],
        ),
      ),
    );
  }
}

/// 🖼️ 缓存头像组件（预设配置）
/// 
/// 专门用于显示用户头像的组件
/// - ✅ 圆形显示
/// - ✅ 自动缓存
/// - ✅ 性能优化
/// - ✅ 无渐变效果
class CachedAvatar extends StatelessWidget {
  /// 头像URL
  final String avatarUrl;
  
  /// 头像大小
  final double size;
  
  /// 占位符图标
  final IconData placeholderIcon;

  const CachedAvatar({
    super.key,
    required this.avatarUrl,
    this.size = 80,
    this.placeholderIcon = Icons.person,
  });

  @override
  Widget build(BuildContext context) {
    return CachedImage(
      imageUrl: avatarUrl,
      width: size,
      height: size,
      isCircle: true,
      placeholderIcon: placeholderIcon,
      placeholderIconSize: size * 0.5,
      errorIcon: placeholderIcon,
      errorIconSize: size * 0.5,
      // 🔥 头像专用优化：缓存尺寸
      memCacheWidth: (size * 2).toInt(), // 2x 像素密度
      memCacheHeight: (size * 2).toInt(),
    );
  }
}

